from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic.base import View

from operation.models import *
from utils.mixin_utils import LoginRequiredMixin
from .models import *
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from organization.models import *
# Create your views here.

class CourseListView(View):
    def get(self,request):
        all_courses = Course.objects.all().order_by('-add_time')

        #热门课程
        hot_courses = Course.objects.all().order_by('-click_num')[:3]

        #搜索课程过滤代码段
        search_keywords = request.GET.get('keywords','')
        if search_keywords:
            all_courses = all_courses.filter(Q(name__icontains=search_keywords)|Q(desc__icontains=search_keywords)|Q(detail__icontains=search_keywords))

        #课程排序
        sort = request.GET.get('sort','')
        if sort:
            if sort == 'students':
                all_courses = all_courses.order_by('-students')
            elif sort == 'hot':
                all_courses = all_courses.order_by('-click_num')


        # 对课程进行分页（调用从github下载的模块pure-pagination功能）
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_courses, 9, request=request)
        courses = p.page(page)
        return render(request,'course-list.html',{
            'all_courses':courses,
            'sort':sort,
            'hot_courses':hot_courses,
        })

class CourseDetailView(View):
    def get(self,request,course_id):
        course = Course.objects.get(id=int(course_id))
        #增加课程点击数
        course.click_num += 1
        course.save()

        has_fav_course = False
        has_fav_org = False
        if request.user.is_authenticated():
            if UserFavorite.objects.filter(user=request.user,fav_id=course_id,fav_type=1):
                has_fav_course = True
            if UserFavorite.objects.filter(user=request.user, fav_id=course.course_org.id, fav_type=2):
                has_fav_org = True


        tag = course.tag
        if tag:
            relate_courses = Course.objects.filter(tag=tag)[:3]
        else:
            relate_courses = []
        return render(request,'course-detail.html',{
            'course':course,
            'relate_courses':relate_courses,
            'has_fav_course':has_fav_course,
            'has_fav_org':has_fav_org
        })

#课程章节信息
class CourseInfoView(LoginRequiredMixin,View):
    def get(self,request,course_id):
        course = Course.objects.get(id=int(course_id))
        course.students +=1
        course.save()

        #查询用户是否已经关联了该课程
        user_has_courses = UserCourse.objects.filter(user=request.user,course=course)
        if not user_has_courses:
            user_has_course = UserCourse(user=request.user,course=course)
            user_has_course.save()

        # 获取学过该课程的学生的其他课程的逻辑代码部分
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)
        course_ids = [user_course.course.id for user_course in all_user_courses]
        course_ids.remove(int(course_id))
        #学过该课程的学生的其他课程取出来
        relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_num')[:3]
        all_resorces = CourseResorce.objects.filter(course=course)
        return render(request,'course-video.html',{
            'course':course,
            'all_resorces':all_resorces,
            'relate_courses':relate_courses,
        })

class CommentsView(LoginRequiredMixin,View):
    def get(self,request,course_id):
        course = Course.objects.get(id=int(course_id))
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)
        course_ids = [user_course.course.id for user_course in all_user_courses]
        course_ids.remove(int(course_id))
        #获取学过该课程的学生的其他课程取出来
        relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_num')[:3]
        all_resorces = CourseResorce.objects.filter(course=course)
        all_comments = CourseComment.objects.filter(course=course)
        return render(request,'course-comment.html',{
            'course':course,
            'all_resorces':all_resorces,
            'all_comments':all_comments,
            'relate_courses': relate_courses,
        })

class AddCommentView(View):
    def post(self,request):
        if not request.user.is_authenticated():
            return HttpResponse("{'status':'fail','msg':'用户未登录！'}", content_type='application/json')
        course_id = int(request.POST.get('course_id',0))
        comments = request.POST.get('comment','')
        if course_id > 0 and comments:
            course_comment = CourseComment()
            course = Course.objects.get(id=course_id)
            course_comment.course = course
            course_comment.comment = comments
            course_comment.user = request.user
            course_comment.save()
            return HttpResponse("{'status':'success','msg':'评论成功！'}", content_type='application/json')
        else:
            return HttpResponse("{'status':'success','msg':'评论失败！'}", content_type='application/json')

#视频播放
class VideoPlayView(View):
    def get(self,request,video_id):
        video = Video.objects.get(id=int(video_id))
        course = video.lesson.course
        course.click_num += 1
        course.save()

        #查询用户是否已经关联了该课程
        user_has_courses = UserCourse.objects.filter(user=request.user,course=course)
        if not user_has_courses:
            user_has_course = UserCourse(user=request.user,course=course)
            user_has_course.save()

        # 获取学过该课程的学生的其他课程的逻辑代码部分
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)
        course_ids = [user_course.course.id for user_course in all_user_courses]
        #学过该课程的学生的其他课程取出来
        relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_num')[:3]
        all_resorces = CourseResorce.objects.filter(course=course)
        return render(request,'course-play.html',{
            'course':course,
            'all_resorces':all_resorces,
            'relate_courses':relate_courses,
            'video':video,
        })